using System;
using System.Collections.Generic;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 短期记忆系统
    /// 存储智能体的当前状态、个人信息和临时工作数据
    /// </summary>
    [System.Serializable]
    public class ScratchMemory
    {
        [Header("智能体基础信息")]
        public string agentName = "";
        public int age = 25;
        public string personality = "";
        public string occupation = "";
        public string background = "";
        
        [Header("当前状态")]
        public DateTime currentTime;
        public Vector3 currentLocation;
        public string currentLocationName = "";
        public string currentAction = "idle";
        public string mood = "neutral";
        public float energy = 1f;
        public float socialBattery = 1f;
        
        [Header("社交状态")]
        public bool isInConversation = false;
        public string conversationPartner = "";
        public string conversationTopic = "";
        public string conversationId = "";
        public List<string> recentConversationPartners;
        
        [Header("计划状态")]
        public string currentPlanId = "";
        public List<PlanItem> currentPlans;
        public List<PlanItem> dailySchedule;
        public DateTime lastPlanUpdate;
        public bool needsReplanning = false;
        
        [Header("反思状态")]
        public int importanceTriggerCurrent = 150;
        public int importanceTriggerMax = 150;
        public DateTime lastReflectionTime;
        public List<string> currentFocusPoints;
        public List<string> recentInsights;
        
        [Header("感知状态")]
        public List<string> currentlyPerceivedEvents;
        public List<string> recentlySeenAgents;
        public List<string> recentlySeenObjects;
        public DateTime lastPerceptionUpdate;
        
        [Header("关系状态")]
        public Dictionary<string, float> relationshipStates; // 名字 -> 关系值(-1到1)
        public Dictionary<string, string> relationshipNotes; // 名字 -> 关系备注
        public List<string> closeFriends;
        public List<string> knownEnemies;
        
        [Header("偏好和习惯")]
        public Dictionary<string, float> preferences; // 偏好 -> 强度
        public List<string> habits;
        public List<string> goals;
        public List<string> fears;
        
        [Header("临时工作数据")]
        public Dictionary<string, object> workingMemory; // 临时数据存储
        public List<string> currentObservations;
        public Queue<string> recentEvents; // 最近事件队列
        
        public ScratchMemory()
        {
            Initialize();
        }
        
        /// <summary>
        /// 初始化短期记忆
        /// </summary>
        private void Initialize()
        {
            currentTime = DateTime.Now;
            currentLocation = Vector3.zero;
            lastReflectionTime = DateTime.Now;
            lastPlanUpdate = DateTime.Now;
            lastPerceptionUpdate = DateTime.Now;
            
            // 初始化集合
            recentConversationPartners = new List<string>();
            currentPlans = new List<PlanItem>();
            dailySchedule = new List<PlanItem>();
            currentFocusPoints = new List<string>();
            recentInsights = new List<string>();
            currentlyPerceivedEvents = new List<string>();
            recentlySeenAgents = new List<string>();
            recentlySeenObjects = new List<string>();
            relationshipStates = new Dictionary<string, float>();
            relationshipNotes = new Dictionary<string, string>();
            closeFriends = new List<string>();
            knownEnemies = new List<string>();
            preferences = new Dictionary<string, float>();
            habits = new List<string>();
            goals = new List<string>();
            fears = new List<string>();
            workingMemory = new Dictionary<string, object>();
            currentObservations = new List<string>();
            recentEvents = new Queue<string>();
            
            // 设置默认值
            SetDefaultValues();
        }
        
        /// <summary>
        /// 设置默认值
        /// </summary>
        private void SetDefaultValues()
        {
            // 默认偏好
            preferences["social_interaction"] = 0.7f;
            preferences["quiet_activities"] = 0.5f;
            preferences["outdoor_activities"] = 0.6f;
            preferences["working"] = 0.8f;
            preferences["learning"] = 0.7f;
            
            // 默认目标
            goals.Add("maintain good relationships");
            goals.Add("complete daily tasks");
            goals.Add("learn new things");
            
            // 默认习惯
            habits.Add("check time regularly");
            habits.Add("greet people when meeting");
            habits.Add("reflect on daily events");
        }
        
        /// <summary>
        /// 从事件更新短期记忆
        /// </summary>
        public void UpdateFromEvent(AgentEvent agentEvent)
        {
            try
            {
                // 更新当前时间和位置
                currentTime = agentEvent.timestamp;
                
                // 如果事件涉及本智能体，更新位置
                if (agentEvent.participants.Contains(agentName))
                {
                    currentLocation = agentEvent.location;
                    currentLocationName = agentEvent.locationName;
                }
                
                // 更新重要性触发器
                importanceTriggerCurrent -= agentEvent.poignancy;
                if (importanceTriggerCurrent < 0)
                {
                    importanceTriggerCurrent = 0;
                }
                
                // 更新感知状态
                UpdatePerceptionState(agentEvent);
                
                // 更新社交状态
                UpdateSocialState(agentEvent);
                
                // 更新工作记忆
                UpdateWorkingMemory(agentEvent);
                
                // 添加到最近事件队列
                AddToRecentEvents(agentEvent.description);
                
                lastPerceptionUpdate = DateTime.Now;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ScratchMemory] Error updating from event: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新感知状态
        /// </summary>
        private void UpdatePerceptionState(AgentEvent agentEvent)
        {
            // 更新当前感知的事件
            if (!currentlyPerceivedEvents.Contains(agentEvent.eventId))
            {
                currentlyPerceivedEvents.Add(agentEvent.eventId);
            }
            
            // 限制感知事件数量
            if (currentlyPerceivedEvents.Count > 10)
            {
                currentlyPerceivedEvents.RemoveAt(0);
            }
            
            // 更新最近见过的智能体
            foreach (var participant in agentEvent.participants)
            {
                if (participant != agentName && !recentlySeenAgents.Contains(participant))
                {
                    recentlySeenAgents.Add(participant);
                }
            }
            
            // 限制列表大小
            if (recentlySeenAgents.Count > 20)
            {
                recentlySeenAgents.RemoveAt(0);
            }
            
            // 如果是交互事件，更新最近见过的对象
            if (agentEvent.eventType == EventType.Interaction && !string.IsNullOrEmpty(agentEvent.objectEntity))
            {
                if (!recentlySeenObjects.Contains(agentEvent.objectEntity))
                {
                    recentlySeenObjects.Add(agentEvent.objectEntity);
                }
                
                if (recentlySeenObjects.Count > 15)
                {
                    recentlySeenObjects.RemoveAt(0);
                }
            }
        }
        
        /// <summary>
        /// 更新社交状态
        /// </summary>
        private void UpdateSocialState(AgentEvent agentEvent)
        {
            if (agentEvent.eventType == EventType.Conversation && agentEvent.participants.Contains(agentName))
            {
                // 更新对话状态
                isInConversation = true;
                conversationId = agentEvent.conversationId;
                
                // 找到对话伙伴
                foreach (var participant in agentEvent.participants)
                {
                    if (participant != agentName)
                    {
                        conversationPartner = participant;
                        
                        // 添加到最近对话伙伴
                        if (!recentConversationPartners.Contains(participant))
                        {
                            recentConversationPartners.Add(participant);
                        }
                        
                        // 更新关系状态
                        UpdateRelationship(participant, 0.1f); // 对话增加好感度
                        
                        break;
                    }
                }
                
                // 限制最近对话伙伴列表大小
                if (recentConversationPartners.Count > 10)
                {
                    recentConversationPartners.RemoveAt(0);
                }
            }
            else if (isInConversation && 
                     (agentEvent.eventType != EventType.Conversation || !agentEvent.participants.Contains(agentName)))
            {
                // 结束对话
                EndConversation();
            }
        }
        
        /// <summary>
        /// 更新关系
        /// </summary>
        public void UpdateRelationship(string otherAgent, float change, string note = "")
        {
            if (string.IsNullOrEmpty(otherAgent) || otherAgent == agentName)
                return;
            
            // 更新关系值
            if (!relationshipStates.ContainsKey(otherAgent))
            {
                relationshipStates[otherAgent] = 0f;
            }
            
            relationshipStates[otherAgent] = Mathf.Clamp(relationshipStates[otherAgent] + change, -1f, 1f);
            
            // 更新备注
            if (!string.IsNullOrEmpty(note))
            {
                relationshipNotes[otherAgent] = note;
            }
            
            // 更新朋友/敌人列表
            var relationshipValue = relationshipStates[otherAgent];
            
            if (relationshipValue >= 0.7f && !closeFriends.Contains(otherAgent))
            {
                closeFriends.Add(otherAgent);
                knownEnemies.Remove(otherAgent); // 从敌人列表移除
            }
            else if (relationshipValue <= -0.7f && !knownEnemies.Contains(otherAgent))
            {
                knownEnemies.Add(otherAgent);
                closeFriends.Remove(otherAgent); // 从朋友列表移除
            }
            else if (relationshipValue > -0.7f && relationshipValue < 0.7f)
            {
                // 中性关系，从两个列表中移除
                closeFriends.Remove(otherAgent);
                knownEnemies.Remove(otherAgent);
            }
        }
        
        /// <summary>
        /// 更新工作记忆
        /// </summary>
        private void UpdateWorkingMemory(AgentEvent agentEvent)
        {
            // 存储最后一个感知到的事件
            workingMemory["lastPerceivedEvent"] = agentEvent;
            workingMemory["lastEventTime"] = agentEvent.timestamp;
            
            // 更新当前观察
            var observation = $"{agentEvent.subject} {agentEvent.predicate} {agentEvent.objectEntity}";
            if (!currentObservations.Contains(observation))
            {
                currentObservations.Add(observation);
            }
            
            // 限制观察列表大小
            if (currentObservations.Count > 5)
            {
                currentObservations.RemoveAt(0);
            }
        }
        
        /// <summary>
        /// 添加到最近事件队列
        /// </summary>
        private void AddToRecentEvents(string eventDescription)
        {
            recentEvents.Enqueue(eventDescription);
            
            // 限制队列大小
            if (recentEvents.Count > 20)
            {
                recentEvents.Dequeue();
            }
        }
        
        /// <summary>
        /// 结束对话
        /// </summary>
        public void EndConversation()
        {
            isInConversation = false;
            conversationPartner = "";
            conversationTopic = "";
            conversationId = "";
        }
        
        /// <summary>
        /// 开始新计划
        /// </summary>
        public void StartNewPlan(PlanItem plan)
        {
            currentPlanId = plan.planId;
            plan.StartExecution();
            
            if (!currentPlans.Contains(plan))
            {
                currentPlans.Add(plan);
            }
            
            lastPlanUpdate = DateTime.Now;
            needsReplanning = false;
            
            // 更新当前行动
            currentAction = plan.action;
        }
        
        /// <summary>
        /// 完成计划
        /// </summary>
        public void CompletePlan(string planId)
        {
            var plan = currentPlans.Find(p => p.planId == planId);
            if (plan != null)
            {
                plan.Complete();
                currentPlans.Remove(plan);
                
                if (currentPlanId == planId)
                {
                    currentPlanId = "";
                    currentAction = "idle";
                }
                
                lastPlanUpdate = DateTime.Now;
            }
        }
        
        /// <summary>
        /// 取消计划
        /// </summary>
        public void CancelPlan(string planId, string reason = "")
        {
            var plan = currentPlans.Find(p => p.planId == planId);
            if (plan != null)
            {
                plan.Cancel(reason);
                currentPlans.Remove(plan);
                
                if (currentPlanId == planId)
                {
                    currentPlanId = "";
                    currentAction = "idle";
                    needsReplanning = true;
                }
                
                lastPlanUpdate = DateTime.Now;
            }
        }
        
        /// <summary>
        /// 添加洞察
        /// </summary>
        public void AddInsight(string insight)
        {
            if (!string.IsNullOrEmpty(insight) && !recentInsights.Contains(insight))
            {
                recentInsights.Add(insight);
                
                // 限制洞察列表大小
                if (recentInsights.Count > 15)
                {
                    recentInsights.RemoveAt(0);
                }
            }
        }
        
        /// <summary>
        /// 添加焦点
        /// </summary>
        public void AddFocusPoint(string focusPoint)
        {
            if (!string.IsNullOrEmpty(focusPoint) && !currentFocusPoints.Contains(focusPoint))
            {
                currentFocusPoints.Add(focusPoint);
                
                // 限制焦点列表大小
                if (currentFocusPoints.Count > 10)
                {
                    currentFocusPoints.RemoveAt(0);
                }
            }
        }
        
        /// <summary>
        /// 更新心情
        /// </summary>
        public void UpdateMood(string newMood, float energyChange = 0f)
        {
            mood = newMood;
            energy = Mathf.Clamp01(energy + energyChange);
            
            // 基于心情调整社交电量
            switch (newMood.ToLower())
            {
                case "happy":
                case "excited":
                    socialBattery = Mathf.Min(1f, socialBattery + 0.1f);
                    break;
                case "tired":
                case "sad":
                    socialBattery = Mathf.Max(0f, socialBattery - 0.1f);
                    break;
            }
        }
        
        /// <summary>
        /// 重置重要性触发器
        /// </summary>
        public void ResetImportanceTrigger()
        {
            importanceTriggerCurrent = importanceTriggerMax;
            lastReflectionTime = DateTime.Now;
        }
        
        /// <summary>
        /// 检查是否需要反思
        /// </summary>
        public bool ShouldReflect()
        {
            return importanceTriggerCurrent <= 0;
        }
        
        /// <summary>
        /// 获取当前状态描述
        /// </summary>
        public string GetCurrentStateDescription()
        {
            var state = $"{agentName} is currently {currentAction} at {currentLocationName}. ";
            state += $"Mood: {mood}, Energy: {energy:F1}. ";
            
            if (isInConversation)
            {
                state += $"In conversation with {conversationPartner}. ";
            }
            
            if (currentPlans.Count > 0)
            {
                state += $"Has {currentPlans.Count} active plans. ";
            }
            
            return state;
        }
        
        /// <summary>
        /// 获取关系描述
        /// </summary>
        public string GetRelationshipDescription(string otherAgent)
        {
            if (!relationshipStates.ContainsKey(otherAgent))
            {
                return "Unknown relationship";
            }
            
            var value = relationshipStates[otherAgent];
            var description = "";
            
            if (value >= 0.7f)
                description = "Close friend";
            else if (value >= 0.3f)
                description = "Friend";
            else if (value >= -0.3f)
                description = "Acquaintance";
            else if (value >= -0.7f)
                description = "Dislike";
            else
                description = "Enemy";
            
            if (relationshipNotes.ContainsKey(otherAgent))
            {
                description += $" ({relationshipNotes[otherAgent]})";
            }
            
            return description;
        }
        
        /// <summary>
        /// 清理过期数据
        /// </summary>
        public void CleanupExpiredData(TimeSpan maxAge)
        {
            var cutoffTime = DateTime.Now - maxAge;
            
            // 清理过期的感知事件
            // 这里需要与事件时间戳配合，简化实现
            if (lastPerceptionUpdate < cutoffTime)
            {
                currentlyPerceivedEvents.Clear();
            }
            
            // 清理过期的观察
            if (currentObservations.Count > 0 && lastPerceptionUpdate < cutoffTime)
            {
                currentObservations.Clear();
            }
        }
        
        /// <summary>
        /// 获取统计信息
        /// </summary>
        public string GetStats()
        {
            return $"Agent: {agentName}, Action: {currentAction}, Mood: {mood}, " +
                   $"Energy: {energy:F1}, Plans: {currentPlans.Count}, " +
                   $"Relationships: {relationshipStates.Count}, " +
                   $"Recent Events: {recentEvents.Count}";
        }
        
        /// <summary>
        /// 重置短期记忆
        /// </summary>
        public void Reset()
        {
            currentAction = "idle";
            mood = "neutral";
            energy = 1f;
            socialBattery = 1f;
            
            EndConversation();
            
            currentPlans.Clear();
            currentPlanId = "";
            needsReplanning = false;
            
            currentlyPerceivedEvents.Clear();
            currentObservations.Clear();
            recentEvents.Clear();
            
            workingMemory.Clear();
            
            lastPerceptionUpdate = DateTime.Now;
            lastPlanUpdate = DateTime.Now;
        }
    }
}